package com.wuxin.ssm.service.impl;


import com.wuxin.ssm.entity.*;
import com.wuxin.ssm.mapper.OrderdetailMapper;
import com.wuxin.ssm.mapper.ProductInfoMapper;
import com.wuxin.ssm.mapper.XmorderMapper;
import com.wuxin.ssm.service.XmorderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @program: ssmwork
 * @ClassName XmorderServiceImpl
 * @description:
 * @author: 李尧坤
 * @create: 2024−12-20 20:41
 * @Version 1.0
 **/
@Service
public class XmorderServiceImpl implements XmorderService {

    @Autowired
    private XmorderMapper xmorderMapper;
    @Autowired
    private OrderdetailMapper orderdetailMapper;
    @Autowired
    private ProductInfoMapper productInfoMapper;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public int save(Xmorder xmorder, String[] pids, List<Carshop> carshopList) {
        int num = 0;

        //保存订单
        xmorderMapper.insertSelective(xmorder);
            for (Carshop c:carshopList){
                //不能超卖
                //订单明细
                Orderdetail orderdetail =new Orderdetail();
                orderdetail.setOid(xmorder.getOid());//订单明细所属的订单编号
                orderdetail.setPid(c.getProd().getpId());
                orderdetail.setPnumber(c.getNumbers());
                //小计
                orderdetail.setPtotal(c.getProd().getpPrice() * c.getNumbers() * 1.0);
                //添加订单明细
                orderdetailMapper.insertSelective(orderdetail);
                //扣减库存
                ProductInfo productInfo = c.getProd();
                productInfo.setpNumber(productInfo.getpNumber()  - c.getNumbers());

                productInfoMapper.updateByPrimaryKey(productInfo);

                //没有出错
                num = 1;
            }
 //       }

        return num;
    }


/*    @Override
    public List<Address> findAddressByid(Integer uid) {
        AddressExample example = new AddressExample();
        example.createCriteria().andUidEqualTo(uid);
        List<Address> addressList = addressMapper.selectByExample(example);
        return addressList;
    }*/

    @Override
    public List<Xmorder> selectOrder(Integer uid) {
        List<Xmorder> xmorderList = xmorderMapper.selectByUidAndAddressid(uid);
        for (Xmorder xmorder : xmorderList) {
            System.out.println(xmorder.getOid());
            List<Orderdetail> detailList = orderdetailMapper.selectByUidAndPid(xmorder.getOid());

            xmorder.setDetailList(detailList);
        }
        return xmorderList;
    }


    //添加订单的同时添加订单明细！！！

}
